/*****************************************************
** Author:
** Date: 2019-11-13
*
*****************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/msg.h>
#include <pthread.h>


struct msgbuf {
    long mtype;
    char payload[32];
};


int mfd;
pthread_t taskid;

/**
 * @brief
 * @param  None
 * @retval None
 */
static void *msgrecv_thread(void *arg)
{
	struct msgbuf m;
	int ret;

	sleep(10);

	ret = msgrcv(mfd, &m, sizeof(struct msgbuf) - sizeof(long), 0, 0);
    tc_log("recv ret %d mtype %ld payload %s", ret, m.mtype, m.payload);

    return NULL;
}

void linuxmsg_test(void)
{
    char path[64];
    int ret;

    char *p = getcwd(path, sizeof(path));
    if (p == NULL) {
        tc_log_err("getcwd failed");
        exit(-1);
    }
    tc_log("p %p, path %s", p, path);

    key_t mid = ftok(path, 'a');
    tc_log("mid 0x%x", mid);

    mfd = msgget(mid, IPC_CREAT | 0666);
    if (mfd == -1) {
        tc_log_err("create msg queue failed");
        exit(-1);
    }
    tc_log("msgget mfd 0x%x", mfd);

    ret = pthread_create(&taskid, NULL, msgrecv_thread, NULL);
    if (ret != 0) {
        tc_log_err("create thread failed");
        goto err;
    }

    struct msgbuf m;
    m.mtype = 1;
    strcpy(m.payload, "hello");

    ret = msgsnd(mfd, &m, sizeof(struct msgbuf) - sizeof(long), 0);
    tc_log("msgsnd ret %d", ret);

    pthread_join(taskid, NULL);

err:
    msgctl(mfd, IPC_RMID, NULL);
}

/* End of file */



